About the project

Write a short description about the course and add a link to your GitHub repository here. This is an R Markdown (.Rmd) file so you can use R Markdown syntax.

I am feeling excited!

Here is the link for my github

https://github.com/vinnu0143/IODS-project

And here is the link to the diary page:

https://vinnu0143.github.io/IODS-project/

I expect to learn about the Open science, sharing the data using Github and learn some programming using R which will make my life easier for doing some statistics im my research work

I heard about this course from yammer group


Regression and model validation

This week we start the data wrangling, do some exploratory examination of the data and fit a simple linear model to the data.

##Reading data Code for data creation is available at: https://github.com/rsund/IODS-project/blob/master/data/create_learning2014.R

Let’s read the data in and make sure that gender is converted to factor

setwd("~/IODS-project")
library(dplyr)

learning2014 <- readxl::read_excel("~/IODS-project/data/learning2014.xlsx") %>% mutate_at(vars(gender), factor)

As can be seen, the structure looks correct now

str(learning2014)
## Classes 'tbl_df', 'tbl' and 'data.frame':    166 obs. of  7 variables:
##  $ gender  : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
##  $ age     : num  53 55 49 53 49 38 50 37 37 42 ...
##  $ attitude: num  3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
##  $ deep    : num  3.58 2.92 3.5 3.5 3.67 ...
##  $ stra    : num  3.38 2.75 3.62 3.12 3.62 ...
##  $ surf    : num  2.58 3.17 2.25 2.25 2.83 ...
##  $ points  : num  25 12 24 10 22 21 21 31 24 26 ...

There are 166 observations of 7 variables of which the gender is converted to factor. Other 6 variables contain integer values

Exploring data

Let’s draw some figures to see how the data looks

pairs(learning2014[!names(learning2014) %in% c("gender")],col=learning2014$gender)

The above pairwise comparison between the variables with male and female gender shown in black and red. There is no clear seperation or correlation between pairs as seen in the graphs. This can be further explained by ggpairs graphs.

library(GGally)
library(ggplot2)
# create a more advanced plot matrix with ggpairs()
ggpairs(learning2014, 
        mapping = aes(col = gender, alpha = 0.3), 
        lower = list(combo = wrap("facethist", bins = 20))
        )

In pairs we are limited to scatter plots but in ggpairs we can visualize various plots for numerical or categorical varibles. From the above graphs highest correlation can be seen between attitude and points.

Linear regression

The highest correlation is between attitude and points, Cor: 0.4365245. Let’s take a closer look.

qplot(attitude, points, data = learning2014) + geom_smooth(method = "lm")

Let’s fit a linear model to the data. Points are explained by attitude. The equation for the model is \[ Y_i = \alpha + \beta_1 X_i + \epsilon_i \] where Y represent points, X is attitude, \(\alpha\) is constant, \(\beta_1\) is regression coefficient for attitude, and \(\epsilon\) is a random term.

Estimation of the model yields the following results:

my_model <- lm(points ~ attitude, data = learning2014)
results <- summary(my_model)
knitr::kable(results$coefficients, digits=3, caption="Regression coefficients")
Regression coefficients
Estimate Std. Error t value Pr(>|t|)
(Intercept) 11.637 1.830 6.358 0
attitude 3.525 0.567 6.214 0

Intercept as well as attitude are statistically significant predictors. Coefficient of determination \(R^2\) = 0.1905537 which is not so high. But what we can interpret from the model is that for every 3.525 increase in attitude leads to 11.637 increase in points. There is a positive correlation etween attitude and points. Probably some more predictors could be added to the model.

Multiple Linear regression

my_model2 <- lm(points ~ attitude + stra + surf, data = learning2014)
results2 <- summary(my_model2)
knitr::kable(results2$coefficients, digits=3, caption="Regression coefficients2")
Regression coefficients2
Estimate Std. Error t value Pr(>|t|)
(Intercept) 11.017 3.684 2.991 0.003
attitude 3.395 0.574 5.913 0.000
stra 0.853 0.542 1.575 0.117
surf -0.586 0.801 -0.731 0.466

Intercept as well as attitude are statistically significant predictors. But the stra and surf are not statistically significant. Surf shows negative correlation with points, whereas stra shows positive correlation along with attitude against points. All combined there is a small improvement in coefficient of determination from using one variable to three. I guess this is the maximum correlation one can get for this dataset.

From the intercept we can infer that for every 3.395 increase in attitude, o.853 increase in stra and 0.586 decrease in surf there is an increase of 11.017 of points.

Coefficient of determination \(R^2\) = 0.2074263 which is not high but .

Diagnostic plots

The diagnostic plots can reveal further the quality of the model.

plot(my_model2, which=c(1,2,5))

From the residuals vs fitted plot we can assume that

The residuals bounce randomly around the 0 line, this suggests that the relationship is linear. There are some values which are very far and is the cause for the line not be a striaght line. These are kind of outliers which raise errors in the dataset.

From the QQ plot one can see that most of the values fall on the straight line. There are some outliers which cause randomness in the dataset.

From the Reiduals vs levarage plot most of the values fall away from the cooks distance but some values like 145, 35,75 looks like they are outliers.

From all the multiple linear regression assessment we can see that the cofficient of determination is too low to consider the model. I would suggest that we have more data for bulding a good model.


Clustering and Classification

This week we are going to see the clustering and classification of Boston data from the MASS package.

Source

Harrison, D. and Rubinfeld, D.L. (1978) Hedonic prices and the demand for clean air. J. Environ. Economics and Management 5, 81–102.

Belsley D.A., Kuh, E. and Welsch, R.E. (1980) Regression Diagnostics. Identifying Influential Data and Sources of Collinearity. New York: Wiley.

load the Boston data and explore

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
library(tidyverse)
## -- Attaching packages -------------------------------------------------------------------------------- tidyverse 1.3.0 --
## v tibble  2.1.3     v purrr   0.3.3
## v tidyr   1.0.0     v stringr 1.4.0
## v readr   1.3.1     v forcats 0.4.0
## -- Conflicts ----------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
## x MASS::select()  masks dplyr::select()
library(corrplot)
## corrplot 0.84 loaded
library(ggplot2)
library(GGally)

# access the MASS package
library(MASS)

# load the data
data("Boston")

# explore the dataset
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
# plot matrix of the variables
pairs(Boston)

The Boston housing dataset consists of 506 rows with 14 columns from suburbs of Boston.These compare the age of the buildings, prices of the buildings, area nitrogen oxide concentrations, average number of rooms for dwelling, proportion of non-retail business acres per town etc.

##Graphical Overview

library(tidyverse)
library(corrplot)
# calculate the correlation matrix and round it
cor_matrix<-cor(Boston) %>% round(digits = 2)

# print the correlation matrix
cor_matrix
##          crim    zn indus  chas   nox    rm   age   dis   rad   tax
## crim     1.00 -0.20  0.41 -0.06  0.42 -0.22  0.35 -0.38  0.63  0.58
## zn      -0.20  1.00 -0.53 -0.04 -0.52  0.31 -0.57  0.66 -0.31 -0.31
## indus    0.41 -0.53  1.00  0.06  0.76 -0.39  0.64 -0.71  0.60  0.72
## chas    -0.06 -0.04  0.06  1.00  0.09  0.09  0.09 -0.10 -0.01 -0.04
## nox      0.42 -0.52  0.76  0.09  1.00 -0.30  0.73 -0.77  0.61  0.67
## rm      -0.22  0.31 -0.39  0.09 -0.30  1.00 -0.24  0.21 -0.21 -0.29
## age      0.35 -0.57  0.64  0.09  0.73 -0.24  1.00 -0.75  0.46  0.51
## dis     -0.38  0.66 -0.71 -0.10 -0.77  0.21 -0.75  1.00 -0.49 -0.53
## rad      0.63 -0.31  0.60 -0.01  0.61 -0.21  0.46 -0.49  1.00  0.91
## tax      0.58 -0.31  0.72 -0.04  0.67 -0.29  0.51 -0.53  0.91  1.00
## ptratio  0.29 -0.39  0.38 -0.12  0.19 -0.36  0.26 -0.23  0.46  0.46
## black   -0.39  0.18 -0.36  0.05 -0.38  0.13 -0.27  0.29 -0.44 -0.44
## lstat    0.46 -0.41  0.60 -0.05  0.59 -0.61  0.60 -0.50  0.49  0.54
## medv    -0.39  0.36 -0.48  0.18 -0.43  0.70 -0.38  0.25 -0.38 -0.47
##         ptratio black lstat  medv
## crim       0.29 -0.39  0.46 -0.39
## zn        -0.39  0.18 -0.41  0.36
## indus      0.38 -0.36  0.60 -0.48
## chas      -0.12  0.05 -0.05  0.18
## nox        0.19 -0.38  0.59 -0.43
## rm        -0.36  0.13 -0.61  0.70
## age        0.26 -0.27  0.60 -0.38
## dis       -0.23  0.29 -0.50  0.25
## rad        0.46 -0.44  0.49 -0.38
## tax        0.46 -0.44  0.54 -0.47
## ptratio    1.00 -0.18  0.37 -0.51
## black     -0.18  1.00 -0.37  0.33
## lstat      0.37 -0.37  1.00 -0.74
## medv      -0.51  0.33 -0.74  1.00
# visualize the correlation matrix
corrplot(cor_matrix, method="circle", type="upper", cl.pos="b", tl.pos="d", tl.cex = 0.6)

Above is the correlation chart of the values. Size of the circle varies according to correlation coefficents. The color of the circle indicates whether it is negatively or positively correlating.

In here it’s visible that rad (index of accessibility to radial highways) correlates positively to tax (full-value property-tax rate per $10,000.) and lstat(lower status of the population (percent)) correlates negatively with medv (median value of owner-occupied homes in $1000s). High positive correlation can be seen between nox and indus.

##Standardizing

# center and standardize variables
boston_scaled <- scale(Boston)

# summaries of the scaled variables
summary(boston_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
# class of the boston_scaled object
class(boston_scaled)
## [1] "matrix"
# change the object to data frame
boston_scaled <- as.data.frame(boston_scaled)

All the data is standardized now using scale function. Compared to earlier summary, the values have changed from positive to negative and minimized in size.

# summary of the scaled crime rate
summary(boston_scaled$crim)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
## -0.419367 -0.410563 -0.390280  0.000000  0.007389  9.924110
# create a quantile vector of crim and print it
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
# create a categorical variable 'crime'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))

# look at the table of the new factor crime
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)

# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

##Creating training and test datasets

# number of rows in the Boston dataset 
n <- nrow(boston_scaled)

# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)

# create train set
train <- boston_scaled[ind,]

# create test set 
test <- boston_scaled[-ind,]

# save the correct classes from test data
correct_classes <- test$crime

# remove the crime variable from test data
test <- dplyr::select(test, -crime)

##Fitting linear discriminat analysis on training set

# linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)

# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2549505 0.2549505 0.2351485 0.2549505 
## 
## Group means:
##                  zn      indus         chas        nox          rm
## low       0.9372798 -0.8911034 -0.157656245 -0.8839830  0.39972132
## med_low  -0.1625395 -0.2466518 -0.081207697 -0.5219507 -0.22366228
## med_high -0.4132207  0.1844098  0.183545696  0.3204804  0.07589269
## high     -0.4872402  1.0170891 -0.004759149  1.0795121 -0.37379445
##                 age        dis        rad        tax     ptratio
## low      -0.9280117  0.8721238 -0.7176123 -0.7241312 -0.42342804
## med_low  -0.3149052  0.3231814 -0.5380946 -0.4562636 -0.04807386
## med_high  0.3388692 -0.3133448 -0.3907129 -0.2842747 -0.16373667
## high      0.8462931 -0.8573636  1.6384176  1.5142626  0.78111358
##                black       lstat        medv
## low       0.37920919 -0.75880796  0.47917252
## med_low   0.31544802 -0.08356637 -0.05539845
## med_high  0.06566312 -0.06850081  0.18150267
## high     -0.76683088  0.91942558 -0.64655119
## 
## Coefficients of linear discriminants:
##                  LD1         LD2          LD3
## zn       0.126208097  0.86669458 -0.786665779
## indus   -0.008061775 -0.35846302  0.291288544
## chas    -0.012577159 -0.05128419  0.002676767
## nox      0.474777266 -0.48640536 -1.481116885
## rm       0.034319342  0.02787627 -0.265150028
## age      0.282788560 -0.35700621 -0.164836633
## dis     -0.061935776 -0.36394216  0.070772846
## rad      3.224613974  0.83261681  0.205478816
## tax     -0.043169709  0.03252265  0.413941607
## ptratio  0.138754589  0.05731380 -0.347120898
## black   -0.098006148  0.02722007  0.170073641
## lstat    0.219990428 -0.15879262  0.397436318
## medv     0.085587333 -0.36335189 -0.248695161
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9557 0.0320 0.0124
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 2)

The plot shows that crime rate stands out from the rest of the data.

# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       17       6        1    0
##   med_low    9      13        1    0
##   med_high   0       4       26    1
##   high       0       0        0   24

##K-Means clustering

The plot is very difficult to understand sos let us interpret it using within cluster sum of squared (wcss).

Form the above graph we can see that the highest drop of total wcss is at cluster number 2. So the best cluster number is 2.

The new graph shows only 2 clusters.

##Bonus

The dataset is reloaded and standardized. The graph below has 4 cluster centers.

## 
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout

## Warning in arrows(x0 = 0, y0 = 0, x1 = myscale * heads[, choices[1]], y1 =
## myscale * : zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(x0 = 0, y0 = 0, x1 = myscale * heads[, choices[1]], y1 =
## myscale * : zero-length arrow is of indeterminate angle and so skipped

The graph above is LDA model with the K-means clusters as target variable and Boston data frame as data. The variable with the longest arrow is nitrogen oxides concentration (nox) and it divides the data frames observations into two separate areas. We can see more closely below.

The two variables showing to be linear separators are variables index of accessibility to radial highways (rad) and Charles River dummy variable (chas) that separate the observations from cluster one from the rest of the group.

##Super bonus

## [1] 404  13
## [1] 13  3

The three matrix produts from previous LDA is inserted into plot_ly function. We can see the above 3D graph which can be moved.


Chapter5: Dimensionality reduction techniques

Introdution

In this chapter we analyse data from UNs Development programs Human Development Index (HDI) and Gender Inequality Index data frames. These are combined together to be a data frame named “Human”. More about the data frame here: [UN development programs: HDI] (http://hdr.undp.org/en/content/human-development-index-hdi)

## 'data.frame':    155 obs. of  9 variables:
##  $ X        : Factor w/ 155 levels "Afghanistan",..: 105 6 134 41 101 54 67 149 28 102 ...
##  $ Edu2.FM  : num  1.007 0.997 0.983 0.989 0.969 ...
##  $ Labo.FM  : num  0.891 0.819 0.825 0.884 0.829 ...
##  $ Life.Exp : num  81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
##  $ Edu.Exp  : num  17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
##  $ GNI      : Factor w/ 155 levels "1,123","1,228",..: 132 109 124 112 113 111 103 123 108 93 ...
##  $ Mat.Mor  : int  4 6 6 5 6 7 9 28 11 8 ...
##  $ Ado.Birth: num  7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
##  $ Parli.F  : num  39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
## [1] 155   9
## [1] "X"         "Edu2.FM"   "Labo.FM"   "Life.Exp"  "Edu.Exp"   "GNI"      
## [7] "Mat.Mor"   "Ado.Birth" "Parli.F"

The data frame consists sof 9 variables and X is the row names i.e. country names.

##            X          Edu2.FM          Labo.FM          Life.Exp    
##  Afghanistan:  1   Min.   :0.1717   Min.   :0.1857   Min.   :49.00  
##  Albania    :  1   1st Qu.:0.7264   1st Qu.:0.5984   1st Qu.:66.30  
##  Algeria    :  1   Median :0.9375   Median :0.7535   Median :74.20  
##  Argentina  :  1   Mean   :0.8529   Mean   :0.7074   Mean   :71.65  
##  Armenia    :  1   3rd Qu.:0.9968   3rd Qu.:0.8535   3rd Qu.:77.25  
##  Australia  :  1   Max.   :1.4967   Max.   :1.0380   Max.   :83.50  
##  (Other)    :149                                                    
##     Edu.Exp           GNI         Mat.Mor         Ado.Birth     
##  Min.   : 5.40   1,123  :  1   Min.   :   1.0   Min.   :  0.60  
##  1st Qu.:11.25   1,228  :  1   1st Qu.:  11.5   1st Qu.: 12.65  
##  Median :13.50   1,428  :  1   Median :  49.0   Median : 33.60  
##  Mean   :13.18   1,458  :  1   Mean   : 149.1   Mean   : 47.16  
##  3rd Qu.:15.20   1,507  :  1   3rd Qu.: 190.0   3rd Qu.: 71.95  
##  Max.   :20.20   1,583  :  1   Max.   :1100.0   Max.   :204.80  
##                  (Other):149                                    
##     Parli.F     
##  Min.   : 0.00  
##  1st Qu.:12.40  
##  Median :19.30  
##  Mean   :20.91  
##  3rd Qu.:27.95  
##  Max.   :57.50  
## 

The summary of the variables shows the data types. Edu2FM is the ratio of secondary education and Labo.FM ratio of labour force participation wrangled in previous exercise. Life Exp shows the life expectancy in different nations where on average people live approximately 71 years. Expected years of education (Edu.exp) shows that in minimum people go to school for is 5 years.

The correlation plot shows that there are strong correlations between the variables. In this graph clearly life expectancy correlates positively with expected years of education.

Principal component analysis (PCA)

To perform PCA the data frame should be numeric and removing the strings i.e. country names this was doen in the earlier step.

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

The above plot has not been standardzed so we see a strange shape. PCA maximizes variance between variables and it requires standardizing.

From the vectors, we can conclude the correlations from aboves correlation matrix. There are clearly three groups of correlation that are recognizable from the vectors. Life expectancy and expected education come close to PC2 and point close to each other. Proportion of womens seats in parliament correlate with labour force participation rate mean.

##Multiple correspondence analysis (MCA)

Here we loaded the tea dataset from FactorMiner library, to perform Multiple Correspondence Analysis.This set contains answers from poll on things related to tea time.

## 'data.frame':    300 obs. of  36 variables:
##  $ breakfast       : Factor w/ 2 levels "breakfast","Not.breakfast": 1 1 2 2 1 2 1 2 1 1 ...
##  $ tea.time        : Factor w/ 2 levels "Not.tea time",..: 1 1 2 1 1 1 2 2 2 1 ...
##  $ evening         : Factor w/ 2 levels "evening","Not.evening": 2 2 1 2 1 2 2 1 2 1 ...
##  $ lunch           : Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
##  $ dinner          : Factor w/ 2 levels "dinner","Not.dinner": 2 2 1 1 2 1 2 2 2 2 ...
##  $ always          : Factor w/ 2 levels "always","Not.always": 2 2 2 2 1 2 2 2 2 2 ...
##  $ home            : Factor w/ 2 levels "home","Not.home": 1 1 1 1 1 1 1 1 1 1 ...
##  $ work            : Factor w/ 2 levels "Not.work","work": 1 1 2 1 1 1 1 1 1 1 ...
##  $ tearoom         : Factor w/ 2 levels "Not.tearoom",..: 1 1 1 1 1 1 1 1 1 2 ...
##  $ friends         : Factor w/ 2 levels "friends","Not.friends": 2 2 1 2 2 2 1 2 2 2 ...
##  $ resto           : Factor w/ 2 levels "Not.resto","resto": 1 1 2 1 1 1 1 1 1 1 ...
##  $ pub             : Factor w/ 2 levels "Not.pub","pub": 1 1 1 1 1 1 1 1 1 1 ...
##  $ Tea             : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
##  $ How             : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
##  $ sugar           : Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
##  $ how             : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ where           : Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ price           : Factor w/ 6 levels "p_branded","p_cheap",..: 4 6 6 6 6 3 6 6 5 5 ...
##  $ age             : int  39 45 47 23 48 21 37 36 40 37 ...
##  $ sex             : Factor w/ 2 levels "F","M": 2 1 1 2 2 2 2 1 2 2 ...
##  $ SPC             : Factor w/ 7 levels "employee","middle",..: 2 2 4 6 1 6 5 2 5 5 ...
##  $ Sport           : Factor w/ 2 levels "Not.sportsman",..: 2 2 2 1 2 2 2 2 2 1 ...
##  $ age_Q           : Factor w/ 5 levels "15-24","25-34",..: 3 4 4 1 4 1 3 3 3 3 ...
##  $ frequency       : Factor w/ 4 levels "1/day","1 to 2/week",..: 1 1 3 1 3 1 4 2 3 3 ...
##  $ escape.exoticism: Factor w/ 2 levels "escape-exoticism",..: 2 1 2 1 1 2 2 2 2 2 ...
##  $ spirituality    : Factor w/ 2 levels "Not.spirituality",..: 1 1 1 2 2 1 1 1 1 1 ...
##  $ healthy         : Factor w/ 2 levels "healthy","Not.healthy": 1 1 1 1 2 1 1 1 2 1 ...
##  $ diuretic        : Factor w/ 2 levels "diuretic","Not.diuretic": 2 1 1 2 1 2 2 2 2 1 ...
##  $ friendliness    : Factor w/ 2 levels "friendliness",..: 2 2 1 2 1 2 2 1 2 1 ...
##  $ iron.absorption : Factor w/ 2 levels "iron absorption",..: 2 2 2 2 2 2 2 2 2 2 ...
##  $ feminine        : Factor w/ 2 levels "feminine","Not.feminine": 2 2 2 2 2 2 2 1 2 2 ...
##  $ sophisticated   : Factor w/ 2 levels "Not.sophisticated",..: 1 1 1 2 1 1 1 2 2 1 ...
##  $ slimming        : Factor w/ 2 levels "No.slimming",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ exciting        : Factor w/ 2 levels "exciting","No.exciting": 2 1 2 2 2 2 2 2 2 2 ...
##  $ relaxing        : Factor w/ 2 levels "No.relaxing",..: 1 1 2 2 2 2 2 2 2 2 ...
##  $ effect.on.health: Factor w/ 2 levels "effect on health",..: 2 2 2 2 2 2 2 2 2 2 ...
## [1] 300  36

To perform MCA, we choose variables Tea, Evening, Dinner, Friends and Where.

## 
## Call:
## MCA(X = tea_time, graph = FALSE) 
## 
## 
## Eigenvalues
##                        Dim.1   Dim.2   Dim.3   Dim.4   Dim.5   Dim.6
## Variance               0.286   0.235   0.204   0.201   0.180   0.152
## % of var.             20.401  16.790  14.599  14.391  12.889  10.842
## Cumulative % of var.  20.401  37.191  51.790  66.181  79.070  89.913
##                        Dim.7
## Variance               0.141
## % of var.             10.087
## Cumulative % of var. 100.000
## 
## Individuals (the 10 first)
##                Dim.1    ctr   cos2    Dim.2    ctr   cos2    Dim.3    ctr
## 1           |  0.492  0.283  0.199 | -0.834  0.986  0.570 |  0.459  0.344
## 2           |  0.492  0.283  0.199 | -0.834  0.986  0.570 |  0.459  0.344
## 3           |  0.062  0.004  0.001 |  0.912  1.179  0.247 | -0.556  0.505
## 4           |  0.881  0.905  0.231 |  0.405  0.232  0.049 | -0.527  0.453
## 5           | -0.019  0.000  0.000 | -0.388  0.214  0.151 | -0.420  0.287
## 6           |  0.881  0.905  0.231 |  0.405  0.232  0.049 | -0.527  0.453
## 7           | -0.160  0.030  0.057 | -0.064  0.006  0.009 | -0.388  0.246
## 8           |  0.154  0.028  0.016 | -0.743  0.782  0.368 |  0.429  0.300
## 9           | -0.046  0.002  0.002 | -0.111  0.017  0.010 |  0.119  0.023
## 10          | -0.213  0.053  0.023 | -0.374  0.198  0.072 |  0.938  1.434
##               cos2  
## 1            0.173 |
## 2            0.173 |
## 3            0.092 |
## 4            0.083 |
## 5            0.176 |
## 6            0.083 |
## 7            0.336 |
## 8            0.123 |
## 9            0.012 |
## 10           0.450 |
## 
## Categories (the 10 first)
##                 Dim.1     ctr    cos2  v.test     Dim.2     ctr    cos2
## black       |   0.136   0.320   0.006   1.348 |  -0.692  10.055   0.157
## Earl Grey   |  -0.324   4.736   0.190  -7.530 |   0.167   1.535   0.051
## green       |   1.591  19.494   0.313   9.671 |   0.573   3.071   0.041
## evening     |  -0.594   8.494   0.185  -7.432 |   0.145   0.617   0.011
## Not.evening |   0.311   4.441   0.185   7.432 |  -0.076   0.323   0.011
## dinner      |   1.393   9.517   0.146   6.610 |   1.993  23.669   0.299
## Not.dinner  |  -0.105   0.716   0.146  -6.610 |  -0.150   1.782   0.299
## friends     |  -0.445   9.058   0.373 -10.562 |   0.349   6.780   0.230
## Not.friends |   0.839  17.070   0.373  10.562 |  -0.658  12.777   0.230
## chain store |   0.135   0.819   0.032   3.116 |  -0.445  10.803   0.353
##              v.test     Dim.3     ctr    cos2  v.test  
## black        -6.849 |   1.431  49.429   0.671  14.159 |
## Earl Grey     3.889 |  -0.487  14.935   0.428 -11.312 |
## green         3.482 |  -0.360   1.397   0.016  -2.190 |
## evening       1.817 |  -0.045   0.068   0.001  -0.561 |
## Not.evening  -1.817 |   0.023   0.035   0.001   0.561 |
## dinner        9.457 |  -0.290   0.576   0.006  -1.376 |
## Not.dinner   -9.457 |   0.022   0.043   0.006   1.376 |
## friends       8.290 |   0.001   0.000   0.000   0.020 |
## Not.friends  -8.290 |  -0.002   0.000   0.000  -0.020 |
## chain store -10.269 |  -0.437  11.936   0.339 -10.065 |
## 
## Categorical variables (eta2)
##               Dim.1 Dim.2 Dim.3  
## Tea         | 0.351 0.172 0.672 |
## evening     | 0.185 0.011 0.001 |
## dinner      | 0.146 0.299 0.006 |
## friends     | 0.373 0.230 0.000 |
## where       | 0.373 0.463 0.343 |

Dinner, tea shop ad green tea variables stand away from the group. They do not come close to the other group. Also dinner and tea shop correlate each other. All the other variales are together at the origin of the dimension values.


Chapter 6. Analysis of longitudinal data

Loading the datasets

library(ggplot2); library(dplyr); library(tidyr)
RATSL <- read.csv(file = "C:/Users/vinnu/Documents/IODS-project/data/RATSL.csv")
RATSL$ID <- factor(RATSL$ID)
RATSL$Group <- factor(RATSL$Group)
str(RATSL)
## 'data.frame':    176 obs. of  5 variables:
##  $ ID    : Factor w/ 16 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
##  $ Group : Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 2 2 ...
##  $ WD    : Factor w/ 11 levels "WD1","WD15","WD22",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ weight: int  240 225 245 260 255 260 275 245 410 405 ...
##  $ Time  : int  1 1 1 1 1 1 1 1 1 1 ...
BPRSL <- read.csv(file = "C:/Users/vinnu/Documents/IODS-project/data/BPRSL.csv")
BPRSL$treatment <- factor(BPRSL$treatment)
BPRSL$subject <- factor(BPRSL$subject)
str(BPRSL)
## 'data.frame':    360 obs. of  5 variables:
##  $ treatment: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
##  $ subject  : Factor w/ 20 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
##  $ weeks    : Factor w/ 9 levels "week0","week1",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ bprs     : int  42 58 54 55 72 48 71 30 41 57 ...
##  $ week     : int  0 0 0 0 0 0 0 0 0 0 ...

In RATS we have three groups on differnet diets.

Analyses on RATS

Graphs

# Graphs of RATS
ggplot(RATSL, aes(x = Time, y = weight, linetype = ID)) +
  geom_line() +
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ Group, labeller = label_both) +
  theme(legend.position = "none") + 
  scale_y_continuous(limits = c(min(RATSL$weight), max(RATSL$weight))) +
  ggtitle("Individual response profiles by group for the RATSL data")

Standardized graphs

RATSL <- RATSL %>%
  group_by(Time) %>%
  mutate(stweigth = (weight - mean(weight))/sd(weight) ) %>%
  ungroup()
glimpse(RATSL)
## Observations: 176
## Variables: 6
## $ ID       <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16...
## $ Group    <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1,...
## $ WD       <fct> WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1...
## $ weight   <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 445...
## $ Time     <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8,...
## $ stweigth <dbl> -1.0011429, -1.1203857, -0.9613953, -0.8421525, -0.88...
ggplot(RATSL, aes(x = Time, y = stweigth, linetype = ID)) +
  geom_line() +
  scale_linetype_manual(values = rep(1:16, times=4)) +
  facet_grid(. ~ Group, labeller = label_both) +
  theme(legend.position = "none") + 
  scale_y_continuous(name = "standardized weigth") +
  ggtitle("Individual response profiles by group for RATSL data after standardization")

Summary graph

# Number of time, baseline (week 0) included
n <- RATSL$Time %>% unique() %>% length()
# Summary data with mean and standard error of bprs by treatment and week 
RATSS <- RATSL %>%
  group_by(Group, Time) %>%
  summarise(mean = mean(weight), se = sd(weight)/sqrt(n) ) %>%
  ungroup()
# Glimpse the data
glimpse(RATSS)
## Observations: 33
## Variables: 4
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,...
## $ Time  <int> 1, 8, 15, 22, 29, 36, 43, 44, 50, 57, 64, 1, 8, 15, 22, ...
## $ mean  <dbl> 250.625, 255.000, 254.375, 261.875, 264.625, 265.000, 26...
## $ se    <dbl> 4.589478, 3.947710, 3.460116, 4.100800, 3.333956, 3.5529...
# Plot the mean profiles
ggplot(RATSS, aes(x = Time, y = mean, linetype = Group, shape = Group)) +
  geom_line() +
  scale_linetype_manual(values = c(1,2,3)) +
  geom_point(size=3) +
  scale_shape_manual(values = c(1,2,3)) +
  geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.4) +
  theme(legend.position = c(0.8,0.4)) +
  scale_y_continuous(name = "mean(weigth) +/- se(weigth)") +
  ggtitle("Mean response profiles for the three groups in the RATS data.")

The mean profiles plot shows that the error bars do not overlap.

Analyses on BPRS data

Plotting

# plotting again 
ggplot(BPRSL, aes(x = week, y = bprs, linetype = subject)) +
  geom_line() +
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ treatment, labeller = label_both) +
  theme(legend.position = "none") + 
  scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs)))

From the plot we see, that between the two treatments there seem to no clear difference. With both bprs measure decreases with time, so treatments seem to work.

Linear regression model

# let's fit a linear regression
BPRS_reg <- lm(bprs ~ week + treatment, data = BPRSL)
# print out a summary of the model
summary(BPRS_reg)
## 
## Call:
## lm(formula = bprs ~ week + treatment, data = BPRSL)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -22.454  -8.965  -3.196   7.002  50.244 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  46.4539     1.3670  33.982   <2e-16 ***
## week         -2.2704     0.2524  -8.995   <2e-16 ***
## treatment2    0.5722     1.3034   0.439    0.661    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 12.37 on 357 degrees of freedom
## Multiple R-squared:  0.1851, Adjusted R-squared:  0.1806 
## F-statistic: 40.55 on 2 and 357 DF,  p-value: < 2.2e-16
BPRS_reg
## 
## Call:
## lm(formula = bprs ~ week + treatment, data = BPRSL)
## 
## Coefficients:
## (Intercept)         week   treatment2  
##     46.4539      -2.2704       0.5722

Treatment2 does not seem to differ from treatmet1.